/**
 * Tiem: 2023-2-9
 * FileName: Hotel After Sales 
 * Editor: Haidong
 */

import React, { Component } from "react";
import { Tabs, Form, Button, Space, Input, InputNumber } from 'antd';
import { postHotelSalesReturnPage, postHotelSalesReturnAgree, postHotelSalesReturnRefuse } from '@/request/hotelOrder';
import SearchHeader from '../component/SearchHeader';
import TheTable from '@/components/TheTable';
import TheButton from "@/components/TheButton";
import TheDialog from '@/components/TheDialog';
import ThePagination from '@/components/ThePagination';
import store from "@/store/store"
import "../style/index.less";

const { TabPane } = Tabs
const { TextArea } = Input;
export default class AfterSales extends Component {
    constructor(props) {
        super();
        this.state = {
            columns: [
                {
                    title: "退单编号",
                    dataIndex: "hotelSalesReturnCode",
                    key: "hotelSalesReturnCode",
                },
                {
                    title: "订单编号",
                    dataIndex: "orderCode",
                    key: "orderCode",
                },
                {
                    title: "用户昵称",
                    dataIndex: "memberName",
                    key: "memberName",
                },
                {
                    title: "用户手机号",
                    dataIndex: "memberPhone",
                    key: "memberPhone",
                },
                {
                    title: "订单金额（元）",
                    dataIndex: "orderTotalPrice",
                    key: "orderTotalPrice",
                    render: (text, render) => {
                        return <React.$Price price={render.orderTotalPrice || 0} />
                    }
                },
                {
                    title: "实付金额（元）",
                    dataIndex: "orderPayPrice",
                    key: "orderPayPrice",
                    render: (text, render) => {
                        return <React.$Price price={render.orderPayPrice || 0} />
                    }
                },
                {
                    title: "退款金额",
                    dataIndex: "returnPrice",
                    key: "returnPrice",
                    render: (text, render) => {
                        return <React.$Price price={render.returnPrice || 0} />
                    }
                },
                // {
                //     title: "退单时间",
                //     dataIndex: "salesGoTime",
                //     key: "salesGoTime",
                // },
                {
                    title: "退单状态",
                    dataIndex: "salesReturnStatus",
                    key: "salesReturnStatus",
                    render: (text, record) => {
                        let label = ''
                        switch (record.salesReturnStatus) {
                            case '1':
                                label = "退款中"
                                break
                            case '4':
                                label = "退款失败"
                                break
                            case '9':
                                label = "退款成功"
                                break
                            case '0':
                                label = "退款关闭"
                                break
                            default:
                                label = "未知退款状态"
                        }
                        return label;
                    }
                },
                {
                    title: "退单原因",
                    dataIndex: "reason",
                    key: "reason",
                },
                {
                    title: "操作",
                    fixed: "right",
                    render: (text, render) => {
                        return (
                            <div>
                                <TheButton hasPermi={['hotel:afterDetail:view']}
                                    onClick={() => this.props.history.push(`/hotel/afterDetail/${render.hotelSalesReturnId}`)}>
                                    查看订单
                                </TheButton>
                                {render.salesReturnStatus === '1' && 
                                    <>
                                        <TheButton hasPermi={['hotel:afterDetail:agree']} onClick={() => this.chargebackConfirm(render.hotelSalesReturnId)}>同意退款</TheButton>
                                        <TheButton hasPermi={['hotel:afterDetail:refuse']} onClick={() => this.chargebackRefused(render.hotelSalesReturnId)}>拒绝退款</TheButton> 
                                    </>
                                }
                            </div>
                        );
                    },
                },
            ],
            tabData: [
                {
                    key: "",
                    tab: '全部'
                },
                {
                    key: '1',
                    tab: '退款中'
                },
                {
                    key: '9',
                    tab: '退款成功'
                },
                {
                    key: '4',
                    tab: '退款失败'
                },
                {
                    key: '0',
                    tab: '退款关闭'
                },
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            salesReturnStatus: '',
            agreevisible:false,
            searchValue:{}
        }
    }

    //Initialization
    componentDidMount() {
        let searchParams = store.getState().searchValue
        if (searchParams.hasOwnProperty('pageNo')) {
            console.log(searchParams);
            // return
            let { pageNo, pageSize, salesReturnStatus, searchValue } = searchParams
            console.log(pageNo,pageSize);
            this.setState({
                searchValue: searchValue,
                pageData:{
                    pageNo: pageNo,
                    pageSize: pageSize
                },
                salesReturnStatus:salesReturnStatus ?? ''
            }, () => {
                this.getData()
            })
        } else {
            console.log(123);
            this.getData()
        }
    }

    //CTRL
    //data
    getData = async () => {
        const { searchValue, salesReturnStatus, pageData } = this.state
        console.log(this.state.pageData);
        let params = {
            ...searchValue, ...pageData, salesReturnStatus
        }
        console.log(params);
        store.dispatch({
            type: 'SaveSearchValues',
            data: {
                ...params
            }
        })
        let res = await postHotelSalesReturnPage({...params,})
        if (res.data && res.code === 0) {
            this.setState({
                pageData: {
                    pageNo: res.pageNo,
                    pageSize: res.pageSize
                },
                dataSource: res.data,
                total: res.totalCount,
                loading: false
            })
        } else {
            this.setState({ loading: false })
        }
    }

    //搜索getValue
    getValue = (value) => {
        this.setState({
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            searchValue: value
        }, () => {
            this.getData()
        })
    }

    //tab切换
    changeKey = (salesReturnStatus) => {
        this.setState({ 
            salesReturnStatus,
            pageData: {
                pageNo: 1,
                pageSize: 10
            }, 
        }, () => {
            this.getData()
        })
    }

    //换页
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo,
                pageSize
            }
        }, () => {
            this.getData()
        })
    }

    //同意退款
    chargebackConfirm = (orderId) => {
        React.$confirm({
            title: "您确认同意此订单退款吗？",
            onOk: async () => {
                this.setState({
                    agreevisible:true,
                    orderId,
                })
            },
        });
    };
    chargebackRefused = (orderId) => {
        this.setState({ visible: true, orderId })
    };
    //同意退款
    agreeOnFinish = async value => {
        this.setState({ btnLoading: true })
        let returnPrice = value.returnPrice*100
        let res = await postHotelSalesReturnAgree({ returnPrice, hotelSalesReturnId: this.state.orderId })
        if (res.code === 0) {
            React.$message({
                type: 'info',
                content: '退款成功'
            })
            this.handleCancel()
            this.getData()
        }
        this.setState({ btnLoading: false })
    }
    //拒绝原因
    onFinish = async value => {
        this.setState({ btnLoading: true })
        let res = await postHotelSalesReturnRefuse({ ...value, hotelSalesReturnId: this.state.orderId })
        if (res.code === 0) {
            React.$message({
                type: 'info',
                content: '拒绝退款成功'
            })
            this.handleCancel()
            this.getData()
        }
        this.setState({ btnLoading: false })
    }
    handleCancel = () => {
        this.setState({
            visible: false,
            agreevisible:false,
            orderId: ''
        })
    }

    //VIEW
    render() {
        const { tabData, visible, agreevisible, btnLoading, columns, dataSource, pageData, total, salesReturnStatus } = this.state
        return (
            <div className="pagebg">
                <Tabs activeKey={salesReturnStatus} onChange={(value) => this.changeKey(value)} tabBarExtraContent={<SearchHeader ref={this.SearchHeaderRef} getValue={this.getValue} />}>
                    {tabData.map(v => {
                        return <TabPane key={v.key} tab={v.tab}>
                            <div className="p-layout-content-pagination">
                                <TheTable scroll={{ x: 'max-content', y: "70vh" }} columns={columns} dataSource={dataSource} />
                                <ThePagination
                                    pageNo={pageData.pageNo}
                                    pageSize={pageData.pageSize}
                                    total={total}
                                    pageChange={this.pageChange}
                                />
                            </div>
                        </TabPane>
                    })}
                </Tabs>
                <TheDialog title="拒绝退款" width={600} visible={visible} footer={null} handleCancel={this.handleCancel} >
                    <Form onFinish={this.onFinish}>
                        <Form.Item name={'refuseReason'} label="拒绝原因" rules={[{ required: true }]}>
                            <TextArea allowClear maxLength={50} showCount autoSize={{ minRows: 6, maxRows: 6 }} />
                        </Form.Item>
                        <Form.Item>
                            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                                <Space>
                                    <Button onClick={this.handleCancel}>取消</Button>
                                    <Button loading={btnLoading} type="primary" htmlType="submit">确认</Button>
                                </Space>
                            </div>
                        </Form.Item>
                    </Form>
                </TheDialog>
                <TheDialog title="同意退款" width={600} visible={agreevisible} footer={null} handleCancel={this.handleCancel} >
                    <Form onFinish={this.agreeOnFinish}>
                        <Form.Item name={'returnPrice'} label="退款金额" rules={[{ required: true }]}>
                            <InputNumber allowClear showCount autoSize={{ minRows: 6, maxRows: 6 }} />
                        </Form.Item>
                        <Form.Item>
                            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                                <Space>
                                    <Button onClick={this.handleCancel}>取消</Button>
                                    <Button loading={btnLoading} type="primary" htmlType="submit">确认</Button>
                                </Space>
                            </div>
                        </Form.Item>
                    </Form>
                </TheDialog>
            </div>
        )
    }

}